package com.sinoglobal.ningxia.activity.shop;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.IBase;
import com.sinoglobal.ningxia.beans.GoodsOrderInfoVo;
import com.sinoglobal.ningxia.beans.RootVo;
import com.sinoglobal.ningxia.beans.ShallShopGoodsDataVo;
import com.sinoglobal.ningxia.dialog.DialogBuilder;
import com.sinoglobal.ningxia.dialog.MDialogMethod;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.fragment.ShoppingGoodsFragment;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.thread.ItktAsyncTask;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.ValidUtil;
import com.tianxia.lib.baseworld.alipay.AlixId;
import com.tianxia.lib.baseworld.alipay.BaseHelper;
import com.tianxia.lib.baseworld.alipay.MobileSecurePayHelper;
import com.tianxia.lib.baseworld.alipay.MobileSecurePayer;
import com.tianxia.lib.baseworld.alipay.ResultChecker;

/**
 * 
 * @author zbl
 * @createdate 2014-6-27 下午2:05:15
 * @Description:精品商城中现金购买填写收货信息
 */
public class PurchaseGoodsActivity extends AbstractActivity implements IBase, OnFocusChangeListener {
	private EditText userNameEd;// 姓名
	private EditText userTelEd;// 电话
	private EditText userAddressEd;// 地址
	private EditText userRemarkEd;// 备注
	private TextView usableAddress;// 可输入的地址长度
	private TextView usableRemark;// 可输入的备注长度
	private TextView nameHint, telHint, addressHint;// 输入错误时的提示语
	private ImageView nameCorrect, telCorrect;//
	private Button payment;// 付款
	private String goodsId;// 商品的id
	private String type;// 1现金 2积分
	private String type2;// 1实物 2活动
	private final String CASH="1";
	private final String INTERGRAL="2";
	private final String SUBMIT_INFO="3";
	private String name;
	private String tel;
	private String address;
	private String remark;
	private String validName;
	private String validPhone;
	private boolean blagName = false;
	private boolean blagTel = false;
	private boolean blagAddress = false;
	private final String PAY_TYPE="1";
	private final String EXCHANGE_TYPE="2";
	private final String SUBMIT_TYPE="3";
	private final String MODE_THIRTY="/30";
	private String orderInfor;// 订单信息，提交给支付宝用于支付
	private ShallShopGoodsDataVo goodsDataVos;// 活动/商品

	private ProgressDialog mProgress = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isTemplate = true;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_purchase_goods);
		titleView.setText(R.string.personal_info);
		// 获取得到的商品的ID和类型
		Intent intent = getIntent();
		goodsDataVos = (ShallShopGoodsDataVo) intent.getSerializableExtra("goodsDataVos");
		goodsId = intent.getStringExtra("goods_id");
		type = intent.getStringExtra("type");
		type2 = intent.getStringExtra("type2");
		init();// 初始化控件
		// 判断填写的基本信息是否正确
		showListener();
		basiciInfor();

	}

	@Override
	public void init() {
//		info = (ScrollView) findViewById(R.id.info);
		userNameEd = (EditText) findViewById(R.id.user_name_ed);
		userTelEd = (EditText) findViewById(R.id.user_tel_ed);
		userAddressEd = (EditText) findViewById(R.id.user_address_ed);
		userRemarkEd = (EditText) findViewById(R.id.user_remark_ed);
		usableAddress = (TextView) findViewById(R.id.a_usable_address);
		usableRemark = (TextView) findViewById(R.id.a_usable_remark);
		nameCorrect = (ImageView) findViewById(R.id.name_correct);
		telCorrect = (ImageView) findViewById(R.id.tel_correct);
		nameHint = (TextView) findViewById(R.id.name_hint);
		telHint = (TextView) findViewById(R.id.tel_hint);
		addressHint = (TextView) findViewById(R.id.address_hint);
		payment = (Button) findViewById(R.id.payment);
		if (PAY_TYPE.equals(type)) {
			payment.setText(getString(R.string.goods_pay));
		} else if (EXCHANGE_TYPE.equals(type)) {
			payment.setText(getString(R.string.sure_to_exchange));
		} else if (SUBMIT_TYPE.equals(type)) {
			payment.setText(getString(R.string.submit_info));
		}

	}

	// 访问网络获取由积分兑换所获取的订单号
	private void ScoreloadInfo() {
		new ItktAsyncTask<Void, Void, GoodsOrderInfoVo>() {

			@Override
			public GoodsOrderInfoVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getGoodsOrderInfoVo(type, type2, goodsId, name, tel, address, remark);
			}

			@Override
			public void after(GoodsOrderInfoVo result) {

				if (result != null) {
					if (Code.CODE_SUCCESS == result.getCode()) {
						final String myscore = result.getMyscore();
						final DialogBuilder dialogBuilder = new DialogBuilder(PurchaseGoodsActivity.this);
						dialogBuilder.Dialogbtn1(getString(R.string.exchange_success), R.layout.dialog_one_button, new MDialogMethod() {

							@Override
							public void dialogOk() {
								//返回兑换实物成功时的积分
								 
								Intent intent = getIntent();
								intent.putExtra("score", myscore);
								setResult(1, intent);
								finish();
							}

							@Override
							public void dialogCancel() {

							}
						});
					} else if (3 == result.getCode()) {
						ShoppingGoodsFragment selectDialog = new ShoppingGoodsFragment(PurchaseGoodsActivity.this, R.style.dialog);// 创建Dialog并设置样式主题
						selectDialog.setCanceledOnTouchOutside(false);// 设置点击Dialog外部任意区域关闭Dialog
						selectDialog.show();
					}
				}
			}

			@Override
			public void exception() {

			}
		}.execute();
	}

	// 访问网络获取由现金购买所获取的订单信息
	private void CashloadInfo() {
		new ItktAsyncTask<Void, Void, GoodsOrderInfoVo>() {

			@Override
			public GoodsOrderInfoVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getGoodsOrderInfoVo(type, goodsId, goodsDataVos.getScore(), goodsDataVos.getConten(), name, tel, address, remark);
			}

			@Override
			public void after(GoodsOrderInfoVo result) {
				if (result != null) {
					// 获取订单信息的字符串

					if (Code.CODE_SUCCESS == result.getCode()) {
						orderInfor = result.getOrderInfor();
						if ("1".equals(type)) {
							// 1.现金点击接入集成支付宝进行第三方支付
							performPay();
						}
					}
				}
			}

			@Override
			public void exception() {

			}
		}.execute();
	}

	@Override
	public void showListener() {

		payment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 判断是否输入框全部输入正确
				if (blagName && blagTel && blagAddress) {

					CashloadInfo();

					// 判断是用现金购买的还是枸杞果兑换的

					// 1.现金购买时进入支付宝进行支付

					if (CASH.equals(type)) {

					} else if (INTERGRAL.equals(type)) {
						// 2.积分兑换时
						ScoreloadInfo(); // 从网络获取数据

					} else if (SUBMIT_INFO.equals(type)) {
						SubmitInfo();
					}

				}
				if (blagTel) {

					// 输入的人一个信息有误（姓名，电话，地址）屏幕就进行闪动
					telHint.setVisibility(View.GONE);
				} else {
					telHint.setVisibility(View.VISIBLE);
				}
				if (blagName) {
					nameHint.setVisibility(View.GONE);
				} else {
					nameHint.setVisibility(View.VISIBLE);
				}
				if (blagAddress) {
					addressHint.setVisibility(View.GONE);
				} else {
					addressHint.setVisibility(View.VISIBLE);
				}

			}

			/**
			 * 
			 * @author zbl
			 * @createdate 2014-7-29 上午11:00:40
			 * @Description:
			 * 
			 */
			private void SubmitInfo() {
				new ItktAsyncTask<Void, Void, RootVo>() {

					@Override
					public RootVo before(Void... params) throws Exception {
						return RemoteImpl.getInstance().SubmitInforActivity(name, tel, address, remark, goodsId);
					}

					@Override
					public void after(RootVo result) {
						if (result != null) {
							if (Code.CODE_SUCCESS != result.getCode()) {
								showShortToastMessage(result.getMessage());
								finish();
							} else {
								showShortToastMessage(result.getMessage());
								Intent intent = getIntent();
								intent.putExtra("success", true);
								setResult(0, intent);
								finish();
							}
						}
					}

					@Override
					public void exception() {

					}

				}.execute();
			}
		});
	}

	private void performPay() {
		// check to see if the MobileSecurePay is already installed.
		// 检测安全支付服务是否安装
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		boolean isMobile_spExist = mspHelper.detectMobile_sp();
		if (!isMobile_spExist) {
			return;
		}

		// start pay for this order.
		// 根据订单信息开始进行支付
		try {
			String info = orderInfor;
			// start the pay.
			// 调用pay方法进行支付
			MobileSecurePayer msp = new MobileSecurePayer();

			boolean bRet = msp.pay(info, mHandler, AlixId.RQF_PAY, this);

			if (bRet) {
				// show the progress bar to indicate that we have started
				// paying.
				// 显示“正在支付”进度条
				closeProgress();
				mProgress = BaseHelper.showProgress(this, null, getString(R.string.paying), false, true);
			} else
				;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	//
	// close the progress bar
	// 关闭进度框
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//
	// the handler use to receive the pay result.
	// 这里接收支付结果，支付宝手机端同步通知
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				String ret = (String) msg.obj;
				ItktLog.e("**-----------------zhifubao------ret-------------------------**" + ret);

				switch (msg.what) {
				case AlixId.RQF_PAY: {
					closeProgress();
					// 处理交易结果
					try {
						// 获取交易状态码，具体状态代码请参看文档
						String tradeStatus = "resultStatus={";
						int imemoStart = ret.indexOf("resultStatus=");
						imemoStart += tradeStatus.length();
						int imemoEnd = ret.indexOf("};memo=");
						tradeStatus = ret.substring(imemoStart, imemoEnd);

						// 先验签通知
						ResultChecker resultChecker = new ResultChecker(ret);
						int retVal = resultChecker.checkSign();
						// 验签失败
						if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
							BaseHelper.showDialog(PurchaseGoodsActivity.this, getString(R.string.prompt_str), getResources().getString(R.string.check_sign_failed), android.R.drawable.ic_dialog_alert);
						} else {// 验签成功。验签成功后再判断交易状态码
							if (tradeStatus.equals("9000"))//
							// 判断交易状态码，只有9000表示交易成功
							{
								BaseHelper.showDialog(PurchaseGoodsActivity.this, getString(R.string.prompt_str), getString(R.string.pay_success), R.drawable.infoicon);
								finish();

							} else {
								BaseHelper.showDialog(PurchaseGoodsActivity.this, getString(R.string.prompt_str),  getString(R.string.pay_fail), R.drawable.infoicon);
							}
						}

					} catch (Exception e) {
						e.printStackTrace();
						BaseHelper.showDialog(PurchaseGoodsActivity.this, getString(R.string.prompt_str), ret, R.drawable.infoicon);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	public static class AlixOnCancelListener implements DialogInterface.OnCancelListener {
		Activity mcontext;

		public AlixOnCancelListener(Activity context) {
			mcontext = context;
		}

		public void onCancel(DialogInterface dialog) {
			mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
		}
	}

	/**
	 * 
	 * @author zbl
	 * @createdate 2014-7-14 上午9:24:47
	 * @Description:判断输入的信息是否正确
	 * @param v
	 * 
	 */
	public void basiciInfor() {
		userNameEd.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				name = s.toString();
				validName = ValidUtil.validName(name);
				nameCorrect.setVisibility(View.VISIBLE);
				if (!validName.equals(MContants.EMPTY_STRING)) {
					nameCorrect.setImageResource(R.drawable.icon_error);
					nameHint.setVisibility(View.VISIBLE);
					blagName = false;
				} else {
					nameCorrect.setImageResource(R.drawable.icon_correct);
					nameHint.setVisibility(View.GONE);
					blagName = true;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		userTelEd.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				tel = s.toString();
				validPhone = ValidUtil.validPhone(tel);
				telCorrect.setVisibility(View.VISIBLE);
				if (!validPhone.equals(MContants.EMPTY_STRING)) {
					telCorrect.setImageResource(R.drawable.icon_error);
					telHint.setVisibility(View.VISIBLE);
					blagTel = false;
				} else {
					telCorrect.setImageResource(R.drawable.icon_correct);
					telHint.setVisibility(View.GONE);
					blagTel = true;
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}
		});

		userAddressEd.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int number;

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				usableAddress.setVisibility(View.VISIBLE);
				usableAddress.setText(MContants.EMPTY_STRING + (30 - s.length()) + MODE_THIRTY);
				temp = s;
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				number = 30 - s.length();
				usableAddress.setText(MContants.EMPTY_STRING + number + MODE_THIRTY);
				if (temp.length() > 30) {
					usableAddress.setTextColor(PurchaseGoodsActivity.this.getResources().getColor(R.color.input_error));
					blagAddress = false;

				} else {
					addressHint.setVisibility(View.GONE);
					blagAddress = true;
					usableAddress.setTextColor(PurchaseGoodsActivity.this.getResources().getColor(R.color.input_correct));
					address = userAddressEd.getText().toString();

				}
			}
		});
		userRemarkEd.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int number;

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				usableRemark.setVisibility(View.VISIBLE);
				usableRemark.setText(MContants.EMPTY_STRING + (30 - s.length()) + MODE_THIRTY);
				temp = s;
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				number = 30 - s.length();
				usableRemark.setText(MContants.EMPTY_STRING + number + MODE_THIRTY);
				if (temp.length() > 30) {
					usableRemark.setTextColor(PurchaseGoodsActivity.this.getResources().getColor(R.color.input_error));
				} else {
					remark = userRemarkEd.getText().toString();
					usableRemark.setTextColor(PurchaseGoodsActivity.this.getResources().getColor(R.color.input_correct));
				}
			}

		});

	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {

	}

}
